#include "stdafx.h"
#include "Diagram.h"

namespace AirCrash {
namespace Calypso {

int maxValue(QMap<QString, int> values) {
	int maxVal(INT_MIN);
	QMapIterator<QString, int> it(values);
	while (it.hasNext()) {
		it.next();
		maxVal = qMax(maxVal, it.value());
	}
	return maxVal;
}

QImage Diagram::createDiagram(QMap<QString, int> values, QString title) {
	int spaceBetween(Config::get("Diagram", "spaceBetween").toInt()),
		heightBetween(Config::get("Diagram", "heightBetween").toInt()),
		margin(Config::get("Diagram", "margin").toInt()),
		width( ((values.size() + 1) * spaceBetween) + (margin * 2) ),
		maximumValue(maxValue(values)),
		drawHeight( ((maximumValue + 1) * heightBetween) ),
		height(drawHeight + (margin * 2));

	QImage resultImage(width, height, QImage::Format_ARGB32);

	QPainter painter(&resultImage);

	painter.fillRect(resultImage.rect(), Qt::white);

	painter.drawText(QRect(0, 0, resultImage.width(), margin), Qt::AlignCenter, title);

	painter.drawLine(QPoint(margin, margin), QPoint(margin, height - margin));
	painter.drawLine(QPoint(margin, height - margin), QPoint(width - margin, height - margin));

	for (int t(1); t <= maximumValue; ++t) {
		painter.drawText(QPoint( margin / 2, margin + (drawHeight - (t * heightBetween)) ), QString::number(t));
		painter.drawLine(QPoint( margin - 5, margin + (drawHeight - (t * heightBetween)) ), QPoint( margin, margin + (drawHeight - (t * heightBetween)) ));
	}

	QMapIterator<QString, int> it(values);
	int step(1);
	int lastValue(-1);

	while (it.hasNext()) {
		it.next();
		
		QString time(it.key());

		painter.setPen(QPen(QBrush(Qt::black), 5));
		painter.drawPoint( margin + (step * spaceBetween), margin + (drawHeight - (it.value() * heightBetween)) );
		
		painter.setPen(Qt::SolidLine);
		if (lastValue != -1) {
			painter.drawLine(QPoint(margin + ((step - 1) * spaceBetween), margin + (drawHeight - (lastValue * heightBetween)) ), 
				QPoint( margin + (step * spaceBetween), margin + (drawHeight - (it.value() * heightBetween)) ));
		}
		lastValue = it.value();

		painter.drawLine(QPoint(margin + (step * spaceBetween), height - margin), QPoint(margin + (step * spaceBetween), height - margin + 5));

		QFontMetrics fm(painter.font());
		QRect br( fm.boundingRect(it.key()) );
		br.moveTopLeft( QPoint((margin + (step * spaceBetween)) - (br.width() / 2), height - margin + 10) );
		br.setHeight(br.height() * 2);
		painter.drawText(br, Qt::AlignCenter, it.key());
		++step;
	}

	return resultImage;
}

}
}